package cn.kailangtu.dataspot.activify;

import android.graphics.Color;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.navigation.fragment.NavHostFragment;
import com.github.mikephil.charting.charts.LineChart;
import com.github.mikephil.charting.components.Description;
import com.github.mikephil.charting.components.Legend;
import com.github.mikephil.charting.components.XAxis;
import com.github.mikephil.charting.components.YAxis;
import com.github.mikephil.charting.data.Entry;
import com.github.mikephil.charting.data.LineData;
import com.github.mikephil.charting.data.LineDataSet;
import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import java.util.ArrayList;
import java.util.List;
import cn.kailangtu.commonevents.eventEntity.FragmentChangedEvent;
import cn.kailangtu.commonevents.eventEntity.OnFragmentChangeEvent;
import cn.kailangtu.commontools.AppVariable;
import cn.kailangtu.dataspot.R;
import cn.kailangtu.dataspot.adapter.ExceptionLogAdapter;
import cn.kailangtu.dataspot.data.ControlTree;
import cn.kailangtu.dataspot.data.ExceptionData;
import cn.kailangtu.dataspot.data.PageIndex;
import cn.kailangtu.dataspot.data.consts.ControlAction;
import cn.kailangtu.dataspot.data.context.SelectContext;
import cn.kailangtu.dataspot.databinding.FragmentExceptionLogBinding;
import cn.kailangtu.dataspot.status;
import cn.kailangtu.dataspot.tasks.BaseTask;
import cn.kailangtu.dataspot.total.TotalData;

public class ExceptionLogFragment extends BaseFragment {

    private FragmentExceptionLogBinding binding;
    private ExceptionLogAdapter adapter = null;
    @Override
    public View onCreateView(
            @NonNull LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState
    ) {

        binding = FragmentExceptionLogBinding.inflate(inflater, container, false);
        return binding.getRoot();

    }

    @Override
    protected void resetPageIndex() {
        status.localPageIndex = PageIndex.H_LOG;
        if (status.localToPlc != 2) {
            BaseTask.toNewPage(status.localPageIndex);
        }
    }

    @Override
    void resetPlatform() {
        if(AppVariable.platform_version == 450 && AppVariable.need_reset_view) {
            commonReset(binding.rlExceptionLogContainer);
        }
    }

    public void onViewCreated(@NonNull View view, Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);

        EventBus.getDefault().post(new FragmentChangedEvent(R.layout.fragment_exception_log));
        initData();
        initListen();
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        binding = null;
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMessageEvent(OnFragmentChangeEvent event) {
        // Do something
        if(R.layout.fragment_factory_setting == event.getTargetFragmentId())
        {
            NavHostFragment.findNavController(ExceptionLogFragment.this)
                    .navigate(R.id.action_ExceptionLogFragment_to_FactorySettingFragment);
        }
        else if(R.layout.fragment_switch_test == event.getTargetFragmentId())
        {
            NavHostFragment.findNavController(ExceptionLogFragment.this)
                    .navigate(R.id.action_ExceptionLogFragment_to_SwitchTestFragment);
        }
        else if(R.layout.fragment_common_setting == event.getTargetFragmentId())
        {
            NavHostFragment.findNavController(ExceptionLogFragment.this)
                    .navigate(R.id.action_ExceptionLogFragment_to_CommonSettingFragment);
        }
        else if(R.layout.fragment_exception_log == event.getTargetFragmentId())
        {
            initData();
        }
        else if(R.layout.fragment_real_picture == event.getTargetFragmentId())
        {
            NavHostFragment.findNavController(ExceptionLogFragment.this)
                    .navigate(R.id.action_ExceptionLogFragment_to_RealPictureFragment);
        }
    }

    private int pageIndex = 0;
    private void initData(){
        if(status.logViewIndex == 1) {
            binding.rlLogViewContainer1.setVisibility(View.VISIBLE);
            binding.rlLogViewContainer2.setVisibility(View.GONE);
            binding.rlLogViewContainer3.setVisibility(View.GONE);
            adapter = new ExceptionLogAdapter(this.getContext(), ExceptionData.getErrLog(pageIndex));
            binding.lvExceptionLog.setAdapter(adapter);
        }
        else if(status.logViewIndex == 2){
            binding.rlLogViewContainer1.setVisibility(View.GONE);
            binding.rlLogViewContainer2.setVisibility(View.VISIBLE);
            binding.rlLogViewContainer3.setVisibility(View.GONE);
            adapter = new ExceptionLogAdapter(this.getContext(), ExceptionData.getSwitchLog(pageIndex));
            binding.lvSwitchLog.setAdapter(adapter);
        }
        else if(status.logViewIndex == 3){
            binding.rlLogViewContainer1.setVisibility(View.GONE);
            binding.rlLogViewContainer2.setVisibility(View.GONE);
            binding.rlLogViewContainer3.setVisibility(View.VISIBLE);
            adapter = new ExceptionLogAdapter(this.getContext(),ExceptionData.getOptionLog(pageIndex));
            binding.lvOptionLog.setAdapter(adapter);
        }
    }


    @Override
    protected int processControlsEvent(int eventType) {
        if(eventType == ControlAction.Selection)
        {
            TextView textView =  this.getActivity().findViewById(controlTree.getSelectNode().getIndex());
            SelectContext.setSelectedView(textView);
        }
        else if(eventType == ControlAction.Entry){
            TextView textView =  this.getActivity().findViewById(controlTree.getSelectNode().getIndex());
            textView.callOnClick();
        }
        return 0;
    }

    @Override
    protected void buildControlTree() {
        controlTree = ControlTree.getExceptionLog();
        controlTree.setSelectNode(null);
    }

    private void initListen(){
        binding.btnExceptionLogNext.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                nextData();
            }
        });
        binding.btnExceptionLogPreview.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                previewData();
            }
        });
    }

    private void nextData(){
        pageIndex++;
        List<ExceptionData> ls =  ExceptionData.getLogData(pageIndex,status.logViewIndex);
        if(ls.size() == 0)
        {
            pageIndex--;
        }
        adapter.setData(ls);
        adapter.notifyDataSetChanged();
    }

    private void previewData(){
        pageIndex--;
        if(pageIndex < 0)
        {
            pageIndex = 0;
        }
        adapter.setData(ExceptionData.getLogData(pageIndex,status.logViewIndex));
        adapter.notifyDataSetChanged();
    }

    public static void setData(LineChart lineChart) {
        int count = 6;
        TotalData.readTotal(count);

        List<Entry> list = new ArrayList<>();
        List<Entry> list2 = new ArrayList<>();
        for (int i = 0; i < count; i++) {
            list.add(new Entry((float)i,TotalData.electricValues[i]));
            list2.add(new Entry((float)i,TotalData.voltageValues[i]));
        }

        LineDataSet set = new LineDataSet(list,"电流值");
        //LineDataSet set2 = new LineDataSet(list2,"电压值");

        // set.setColor(Color.WHITE);
        // set2.setColor(Color.WHITE);
        Legend legend1 = lineChart.getLegend();
        legend1.setTextColor(Color.WHITE);
        legend1.setTextSize(8f);

        legend1.setOrientation(Legend.LegendOrientation.HORIZONTAL);
        legend1.setVerticalAlignment(Legend.LegendVerticalAlignment.TOP);
        legend1.setHorizontalAlignment(Legend.LegendHorizontalAlignment.CENTER);

        //标志在文字的位置--左侧
        legend1.setDirection(Legend.LegendDirection.LEFT_TO_RIGHT);

        Description description = lineChart.getDescription();
        description.setEnabled(false);
        lineChart.setDescription(description);


        set.setLineWidth(4f);
        set.setCircleRadius(1.5f);
        set.setMode(LineDataSet.Mode.CUBIC_BEZIER);
        set.setCircleColor(Color.BLUE);
        set.setColor(Color.BLUE);
        set.setDrawFilled(false);
        set.setDrawCircleHole(false);

        set.setValueTextSize(10f);



        //set2.setDrawCircleHole(true);

        /*
        set2.setLineWidth(1f);
        set2.setCircleRadius(1.5f);
        set2.setMode(LineDataSet.Mode.CUBIC_BEZIER);

        set2.setDrawFilled(false);
        set2.setDrawCircleHole(false);

        set2.setValueTextSize(10f);
        set2.setColor(Color.rgb(0,208,255));
        set2.setCircleColor(Color.rgb(0,208,255));

      */

        LineData data = new LineData(set);



        data.setDrawValues(false);
        data.setValueTextColor(Color.RED);
        data.setValueTextSize(15f);



        XAxis xAxis = lineChart.getXAxis();
        xAxis.setEnabled(true);
        xAxis.setPosition(XAxis.XAxisPosition.BOTTOM);
        xAxis.setLabelCount(5);
        xAxis.setTextSize(8f);
        xAxis.setTextColor(Color.rgb(0x04,0xAD,0xFF));
        xAxis.setDrawAxisLine(true);
        xAxis.setDrawGridLines(false);
        xAxis.setAxisMaximum(5f);
        xAxis.setAxisMinimum(0f);

        xAxis.setAxisLineColor(Color.rgb(0x04,0xAD,0xFF));
        xAxis.setGridColor(Color.rgb(0x04,0xAD,0xFF));

        /*
        ValueFormatter valueFormatter = new ValueFormatter() {
            @Override
            public String getFormattedValue(float value) {
                return ""+getLabel((int)value);
            }
        };


        xAxis.setValueFormatter(valueFormatter);
        */


        YAxis leftyAxis =lineChart.getAxisLeft();
        leftyAxis.setDrawAxisLine(false);
        leftyAxis.setLabelCount(5);
        leftyAxis.setDrawLabels(true);
        leftyAxis.setDrawZeroLine(false);
        leftyAxis.setTextColor(Color.rgb(0x04,0xAD,0xFF));
        leftyAxis.setAxisLineColor(Color.rgb(0x04,0xAD,0xFF));
        leftyAxis.setGridColor(Color.rgb(0x04,0xAD,0xFF));
        leftyAxis.setAxisMaximum(100f);
        leftyAxis.setAxisMinimum(0f);
        YAxis rightyAxis = lineChart.getAxisRight();
        rightyAxis.setEnabled(false);



        lineChart.setData(data);


        //lineChart.get

    }
}